import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:mobkit_dashed_border/mobkit_dashed_border.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/upload_video_model.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';

class PicSelectedView extends StatefulWidget {
  final double? width;
  final double? height;
  final UploadVideoModel uploadModel;
  final String? title;
  final Function()? selectAction;

  const PicSelectedView({
    Key? key,
    required this.uploadModel,
    this.width,
    this.height,
    this.title,
    this.selectAction,
  });

  @override
  State<StatefulWidget> createState() {
    return _PicSelectedViewState();
  }
}

class _PicSelectedViewState extends State<PicSelectedView> {
  UploadVideoModel get uploadModel => widget.uploadModel;

  List<String> get picList => uploadModel.localPicList;
  String? get videoPath => uploadModel.videoLocalPath;
  GraffitiModel? get stripModel => uploadModel.graffitiModel;

  @override
  void initState() {
    super.initState();
  }

  void _onDeleteItem(int index) {
    if (index < picList.length) {
      picList.removeAt(index);
    }
    uploadModel.updateStripModel(null);
    widget.selectAction?.call();
    setState(() {});
  }

  void addItemCallback() async {
    var list = await _pickImg();
    if (list.isEmpty) {
      showToast("请选择图片");
      return;
    }
    picList.clear();
    picList.addAll(list);

    widget.selectAction?.call();
    setState(() {});
  }

  Future<List<String>> _pickImg() async {
    List<String> ret = [];
    var listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: AppColors.primaryColor),
      galleryMode: GalleryMode.image,
      showCamera: true,
    );
    if (listMedia.isEmpty) return ret;

    if (Platform.isAndroid) {
      for (var index = 0; index < listMedia.length; index++) {
        var path = listMedia[index].path;
        if (path != null) {
          ret.add(path);
        }
      }
    } else {
      for (var index = 0; index < listMedia.length; index++) {
        String path = listMedia[index].path ?? "";
        var file = File(path);
        var size = await file.readAsBytes();
        //大于300kb的图需要压缩
        if ((size.length / 1024) > 300) {
          var compressFile = await FlutterNativeImage.compressImage(path, percentage: 40, quality: 50);
          path = compressFile.path;
        }
        if (path.isNotEmpty) {
          ret.add(path);
        } else {
          showToast("添加图片失败");
        }
      }
    }
    return ret;
  }

  @override
  Widget build(BuildContext context) {
    var picWidgetList = <Widget>[];

    for (var index = 0; index < picList.length; index++) {
      var curWidget = GestureDetector(
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.file(
                File(picList[index]),
                width: widget.width,
                height: widget.height,
                fit: BoxFit.cover,
              ),
            ),
            Positioned(
              top: 0,
              right: 0,
              child: InkWell(
                child: Container(
                  padding: const EdgeInsets.all(6),
                  child: Image.asset(
                    "close_grey.png".commonImgPath,
                    width: 14,
                    height: 14,
                  ),
                ),
                onTap: () => _onDeleteItem(index),
              ),
            ),
          ],
        ),
        onTap: () {
          ImagePickers.previewImages(picList, index);
        },
      );
      picWidgetList.add(curWidget);
    }

    if (picWidgetList.isEmpty) {
      picWidgetList.add(
        GestureDetector(
          onTap: addItemCallback,
          child: Container(
            width: widget.width,
            height: widget.width,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xff1F2031),
              border: DashedBorder.fromBorderSide(
                dashLength: 2,
                side: BorderSide(color: Color(0xff999999)),
              ),
              borderRadius: BorderRadius.all(Radius.circular(3)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  'add_grey.png'.communityPath,
                  width: 24,
                  color: Color(0xffDCDCDC),
                ),
                4.sizeBoxH,
                Text(
                  "上传图片",
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xff999999),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return GridView(
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
      ),
      children: picWidgetList,
    );
  }
}
